<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic;


use app\adminapi\logic\auth\AdminLogic;
use app\common\logic\BaseLogic;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\auth\AdminTeam;
use app\common\model\auth\SystemRole;
use app\common\model\order\Order;
use app\common\model\promotion\PromotionLink;
use app\common\model\recycle_report\RecycleReport;
use app\common\service\ConfigService;
use app\common\service\FileService;
use think\facade\Log;


/**
 * 工作台
 * Class WorkbenchLogic
 * @package app\adminapi\logic
 */
class WorkbenchLogic extends BaseLogic
{
    /**
     * @notes 工作套
     * @param $adminInfo
     * @return array
     * @author 段誉
     * @date 2021/12/29 15:58
     */
    public static function index($admin,$platform)
    {
        return [
            // 版本信息
            'version' => self::versionInfo(),
            // 今日数据
            'today'   => self::today($admin,$platform),
            // 常用功能
            'menu'    => self::menu(),
            // 近15日访客数
            'visitor' => self::visitor(),
            // 服务支持
            'support' => self::support()
        ];
    }


    /**
     * @notes 常用功能
     * @return array[]
     * @author 段誉
     * @date 2021/12/29 16:40
     */
    public static function menu(): array
    {
        return [
            [
                'name'  => '管理员',
                'image' => FileService::getFileUrl(config('project.default_image.menu_admin')),
                'url'   => '/permission/admin'
            ],
            [
                'name'  => '角色管理',
                'image' => FileService::getFileUrl(config('project.default_image.menu_role')),
                'url'   => '/permission/role'
            ],
            [
                'name'  => '部门管理',
                'image' => FileService::getFileUrl(config('project.default_image.menu_dept')),
                'url'   => '/organization/department'
            ],
            [
                'name'  => '字典管理',
                'image' => FileService::getFileUrl(config('project.default_image.menu_dict')),
                'url'   => '/dev_tools/dict'
            ],
            [
                'name'  => '代码生成器',
                'image' => FileService::getFileUrl(config('project.default_image.menu_generator')),
                'url'   => '/dev_tools/code'
            ],
            [
                'name'  => '素材中心',
                'image' => FileService::getFileUrl(config('project.default_image.menu_file')),
                'url'   => '/material/index'
            ],
            [
                'name'  => '菜单权限',
                'image' => FileService::getFileUrl(config('project.default_image.menu_auth')),
                'url'   => '/permission/menu'
            ],
            [
                'name'  => '网站信息',
                'image' => FileService::getFileUrl(config('project.default_image.menu_web')),
                'url'   => '/setting/website/information'
            ],
        ];
    }


    /**
     * @notes 版本信息
     * @return array
     * @author 段誉
     * @date 2021/12/29 16:08
     */
    public static function versionInfo(): array
    {
        return [
            'version' => config('project.version'),
            'website' => config('project.website.url'),
            'name'    => ConfigService::get('website', 'name'),
            'based'   => 'vue3.x、ElementUI、MySQL',
            'channel' => [
                'website' => 'https://www.likeadmin.cn',
                'gitee'   => 'https://gitee.com/likeadmin/likeadmin_php',
            ]
        ];
    }


    /**
     * @notes 今日数据
     *
     * @return int[]
     * @author 段誉
     * @date 2021/12/29 16:15
     */
    public static function today($admin,$platform): array
    {
        // TODO 管理员权限控制
        $isRoot    = $admin['is_root'] ?? 0;
        $pAdminIds = AdminLogic::getPermissionAdminIds($admin);
        $map = [];
        if (!empty($platform)){
            $map['platform'] = $platform;
        }
        if ($isRoot) {    // 是否超级管理员
            $orders          = Order::where('pay_time', '>=', strtotime(date('Y-m-d 00:00:00')))->where('status', 1)->where($map)->select()->toArray();
            $yesterdayOrders = Order::where('pay_time', '>=', strtotime(date('Y-m-d 00:00:00', strtotime('-1 day'))))
                ->where('pay_time', '<=', strtotime(date('Y-m-d 23:59:59', strtotime('-1 day'))))
                ->where('status', 1)->where($map)->select()->toArray();
            $thirtyOrders    = Order::where('pay_time', '>=', strtotime(date('Y-m-d 00:00:00', strtotime("-30 day"))))
                ->where('status', 1)->where($map)->select()->toArray();

        } else {
            $map2 = [];
            if (!empty($platform)){
                $map2['o.platform'] = $platform;
            }
            $orders = Order::alias('o')
                ->leftJoin('order_callback c', 'o.id = c.order_id')
                ->where('o.pay_time', '>=', strtotime(date('Y-m-d 00:00:00')))
                ->where('c.admin_id', 'in', $pAdminIds)
                ->where('o.status', 1)
                ->where($map2)
                ->select()
                ->toArray();

            $yesterdayOrders = Order::alias('o')
                ->leftJoin('order_callback c', 'o.id = c.order_id')
                ->where('o.pay_time', '>=', strtotime(date('Y-m-d 00:00:00', strtotime('-1 day'))))
                ->where('o.pay_time', '<=', strtotime(date('Y-m-d 23:59:59', strtotime('-1 day'))))
                ->where('c.admin_id', 'in', $pAdminIds)
                ->where('o.status', 1)
                ->where($map2)
                ->select()
                ->toArray();

            $thirtyOrders = Order::alias('o')
                ->leftJoin('order_callback c', 'o.id = c.order_id')
                ->where('o.pay_time', '>=', strtotime(date('Y-m-d 00:00:00', strtotime("-30 day"))))
                ->where('c.admin_id', 'in', $pAdminIds)
                ->where('o.status', 1)
                ->where($map2)
                ->select()
                ->toArray();
        }


        $total_money = round(array_sum(array_column($orders, 'money')), 2);
        $order_count = count($orders);

        $yesterday_total_money = round(array_sum(array_column($yesterdayOrders, 'money')), 2);
        $thirty_total_money    = round(array_sum(array_column($thirtyOrders, 'money')), 2);
        $promotion_link_id_arr = PromotionLink::where('admin_id','in',$pAdminIds)->where($map)->column('id');

//        $query = RecycleReport::with('link')->whereDay('count_date');
        $query = RecycleReport::alias('rr')->join('promotion_link pl', 'rr.promotion_link_id = pl.id', 'INNER')->whereDay('count_date');
        if ($isRoot) {
            $report = $query->select()->toArray();
        } else {
            $report = $query->where('pl.id','in',$promotion_link_id_arr)->where('pitcher_id', 'in', $pAdminIds)->select()->toArray();
        }

        $new_fans_num            = getSum($report, 'new_fans_num');
        $add_desktop_num         = getSum($report, 'add_desktop_num');
        $new_fans_pay_num        = getSum($report, 'new_fans_pay_num');
        $new_fans_recharge_money = getSum($report, 'new_fans_recharge_money');


        return [
            'time'                    => date('Y-m-d H:i:s'),
            // 今日总收入
            'today_money'             => $total_money,
            // 昨日充值
            'yesterday_money'         => $yesterday_total_money,
            // 30日充值
            'thirty_money'            => $thirty_total_money,
            // 今日充值笔数
            'order_count'             => $order_count,
            // 今日新增用户数
            'new_fans_num'            => $new_fans_num,
            // 今日新增加桌人数
            'add_desktop_num'         => $add_desktop_num,
            // 今日新用户充值人数
            'new_fans_pay_num'        => $new_fans_pay_num,
            // 今日新用户充值金额
            'new_fans_recharge_money' => $new_fans_recharge_money
        ];
    }


    /**
     * @notes 访问数
     * @return array
     * @author 段誉
     * @date 2021/12/29 16:57
     */
    public static function visitor(): array
    {
        $num  = [];
        $date = [];
        for ($i = 0; $i < 15; $i++) {
            $where_start = strtotime("- " . $i . "day");
            $date[]      = date('Y/m/d', $where_start);
            $num[$i]     = rand(0, 100);
        }

        return [
            'date' => $date,
            'list' => [
                ['name' => '访客数', 'data' => $num]
            ]
        ];
    }


    /**
     * @notes 服务支持
     * @return array[]
     * @author 段誉
     * @date 2022/7/18 11:18
     */
    public static function support()
    {
        return [
            [
                'image' => FileService::getFileUrl(config('project.default_image.qq_group')),
                'title' => '官方公众号',
                'desc'  => '关注官方公众号',
            ],
            [
                'image' => FileService::getFileUrl(config('project.default_image.customer_service')),
                'title' => '添加企业客服微信',
                'desc'  => '想了解更多请添加客服',
            ]
        ];
    }

}
